<template>
	<section>
		<ul class="ml10 mr10 mt20 fontc0">
			<li class="line tl lh25">
				<span
					class="red dbi fs14"
				>账户余额: {{gold?userInfo.scoreUsable:userInfo.moneyUsable|formatMoney()}}</span>
			</li>
			<li class="clearfix line">
				<strong class="fl">交易模式</strong>
				<div class="fl clearfix">
					<span class="fl box fix mr5" :class="{active:this.jiao==false}" @click="setYuan">圆</span>
					<span
						class="fl box fix mr5"
						v-show="curVariety.isDomestic==0 && this.channelInfo.enableYJFlagShow && this.channelInfo.enableYJFlagShow.includes('H5')"
						:class="{active:this.jiao==true}"
						@click="setJiao"
					>角</span>
				</div>
			</li>
			<li class="clearfix line">
				<strong class="fl">交易手数</strong>
				<div class="fl">
					<span
						class="fl box fix mr5"
						:class="{active:curHand==hand}"
						@click="clickHand(hand)"
						:key="idx"
						v-for="(hand,idx) in curHandArr"
					>
						{{hand
						+ '手'}}
					</span>
				</div>
			</li>
			<li class="clearfix line">
				<strong class="fl">交易手数</strong>
				<div class="fl">
					<em
						class="fl cube iconfont icon-minus fs10"
						:class="{active:curHand>minHand}"
						@click="subCurHand"
					></em>
					<input class="fl lh25" v-model="filterCurHand" type="number">
					<em
						class="fl cube iconfont icon-plus fs10"
						:class="{active:curHand<maxHand}"
						@click="addCurHand"
					></em>
				</div>
			</li>
			<li class="clearfix flex line">
				<strong class="fl">触发止损(￥)</strong>
				<div class="fl flex1">
					<span
						class="fl box mr5"
						:class="{active:idx==curAssetsIdx}"
						@click="changeStopLossBeat(idx)"
						:key="idx"
						v-show="idx>2?!foldStopLossBeat:true"
						v-for="(money,idx) in stopLossBeat"
					>{{money*rate*curHand*getBasePeiZi.ratio|formatMoney()}}</span>
					<span
						class="fl arrow-box mr5 iconfont"
						:class="foldStopLossBeat?'icon-zhankaixia':'icon-shouqishang'"
						@click="foldStopLossBeat=!foldStopLossBeat"
					></span>
				</div>
			</li>
			<li class="clearfix flex line">
				<strong class="fl">触发止盈(￥)</strong>
				<div class="fl flex1">
					<span
						class="fl box mr5"
						:class="{active:curStopWinBeat==money}"
						@click="changeStopWinBeat(money)"
						:key="idx"
						v-show="idx>2?!foldStopWinBeat:true"
						v-for="(money,idx) in stopWinBeat"
					>{{money*rate*curHand*getBasePeiZi.ratio|formatMoney()}}</span>

					<span
						class="fl arrow-box iconfont"
						:class="foldStopWinBeat?'icon-zhankaixia':'icon-shouqishang'"
						@click="foldStopWinBeat=!foldStopWinBeat"
					></span>
				</div>
			</li>
			<li class="clearfix fee">
				<strong class="fl">合计支付</strong>
				<div class="fl clearfix">
					<span class="fl">￥{{totleMoney*getBasePeiZi.ratio|formatMoney()}}</span>
					<span
						class="fl iconfont ml10"
						:class="foldText?'icon-zhankaixia':'icon-shouqishang'"
						@click="foldText=!foldText"
					></span>
				</div>
			</li>
			<li class="clearfix fee" v-show="!foldText">
				<strong class="fl">触发保证金</strong>
				<div class="fl clearfix">
					<span class="fl">￥{{marginBeat*curHand*rate*getBasePeiZi.ratio|formatMoney()}}</span>
				</div>
			</li>
			<li class="clearfix fee" v-show="!foldText">
				<strong class="fl">交易综合费</strong>
				<div class="fl clearfix">
					<span class="fl">￥{{fee*curHand*rate*getBasePeiZi.ratio|formatMoney()}}</span>
				</div>
			</li>
		</ul>
		<div class="buy-button mt10">
			<p class="lh40 up fs16 bgred ml10 mr10 br4" @click.stop="submitOrder('up')">
				买涨
				<span class="fs14">{{this.curQuota.askPrice|formatPoint(this.curVariety.marketPoint)}}</span>
			</p>
			<p class="lh40 down fs16 bggreen ml10 mr10 br4" @click.stop="submitOrder('down')">
				买跌
				<span class="fs14">{{this.curQuota.bidPrice|formatPoint(this.curVariety.marketPoint)}}</span>
			</p>
		</div>
	</section>
</template>
<script>
import { mapState, mapGetters, mapMutations } from 'vuex'
import { orderNewOrderSubmitNewOrder } from '@api/order.js'
export default {
	name: 'Base',
	data() {
		return {
			imgBuyUp: './static/imgs/buyup.svg',
			imgBuyDown: './static/imgs/buydown.svg',

			curAssetsIdx: 1,
			//是否是角模式
			jiao: false,
			//当前倍率 角模式时为0.1
			rate: 1,
			curHand: 0,
			curStopWinBeat: 0,
			//能否下单
			orderKey: true,

			// 折叠内容
			foldText: true,
			foldStopLossBeat: true,
			foldStopWinBeat: true
		}
	},
	mounted() {},
	computed: {
		...mapState(['curQuota', 'userInfo','topupAuth','gold', 'curVariety', 'channelInfo']),
		...mapGetters(['getBasePeiZi']),
		// 加一层过滤设置 curHand
		filterCurHand: {
			get() {
				return this.curHand
			},
			set(hand) {
				if (hand) {
					hand = parseFloat(hand)
				} else {
					hand = 0
				}
				this.curHand = hand
			}
		},
		curHandArr() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].handsMultiple
			} else {
				return []
			}
		},
		stopLossBeat() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets.map((value, idx, arr) => {
					return value.stopLossBeat
				})
			} else {
				return []
			}
		},
		stopWinBeat() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].stopWinBeat
			} else {
				return []
			}
		},
		minHand() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].minHands
			} else {
				return 0
			}
		},
		maxHand() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].maxHands
			} else {
				return 0
			}
		},
		marginBeat() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].marginBeat
			} else {
				return 0
			}
		},
		fee() {
			if (this.getBasePeiZi) {
				return this.getBasePeiZi.fees
			} else {
				return 0
			}
		},
		totleMoney() {
			return (this.marginBeat + this.fee) * this.curHand * this.rate
		}
	},
	methods: {
		...mapMutations(['setToOrder', 'setOrderType']),
		subCurHand() {
			if (this.curHand > this.minHand) {
				this.curHand = this.curHand - 1
				this.curHand = +this.curHand
			}
		},
		addCurHand() {
			if (this.curHand < this.maxHand) {
				this.curHand = +this.curHand + 1
				this.curHand = +this.curHand
			}
		},
		clickHand(hand) {
			if (hand) {
				this.curHand = hand
			}
		},
		changeStopLossBeat(idx) {
			this.curAssetsIdx = idx
			this.curStopWinBeat = this.getBasePeiZi.assets[this.curAssetsIdx].stopWinBeat[1]
		},
		changeStopWinBeat(money) {
			this.curStopWinBeat = money
		},
		setYuan() {
			if (this.jiao == true) {
				this.jiao = false
				this.rate = 1
			}
		},
		setJiao() {
			if (this.jiao == false) {
				this.jiao = true
				this.rate = 0.1
			}
		},
		submitOrder(direction) {
			if (!this.orderKey) return
			// Toast('市价模式下单中');
			Indicator.open({
				text: '提交订单中...',
				spinnerType: 'fading-circle'
			})
			if (direction == 'up') {
				var direction = 1
				var price = this.curQuota.bidPrice
			} else if (direction == 'down') {
				var direction = 0
				var price = this.curQuota.askPrice
			} else {
				alert('direction 出错')
				return
			}
			const params = {
				handsNum: this.curHand,
				payType: this.gold ? 0 : 1,
				varietyId: this.curVariety.varietyId,
				orderPrice: price,
				stopWinBeat: this.curStopWinBeat,
				assetsId: this.getBasePeiZi.assets[this.curAssetsIdx].assetsId,
				direction: direction,
				orderMode: 1,
				tradeMode: this.jiao ? 1 : 0 //0元1角
			}
            this.orderKey = false
            Indicator.open('提交订单中')
			orderNewOrderSubmitNewOrder(params)
				.then(res => {
					if (res.code == 200) {
						setTimeout(() => {
                            this.$store.dispatch('getUserInfo')
                        }, 1000);
						if (params.payType === 1) {
							_hmt.push([
								'_trackOrder',
								{
									orderId: new Date().toString(),
									orderTotal: +this.totleMoney * this.getBasePeiZi.ratio,
									skuId: window.userPhone,
									skuName: '市价,' + new Date().toString(),
									category: this.curVariety.varietyName,
									Quantity: +params.handsNum * (params.tradeMode === 1 ? 0.1 : 1),
									item: [
										{
											skuId: window.userPhone,
											skuName: '市价,' + new Date().toString(),
											category: this.curVariety.varietyName,
											Price: +(this.marginBeat + this.fee) * this.getBasePeiZi.ratio,
											Quantity: +params.handsNum * (params.tradeMode === 1 ? 0.1 : 1)
										}
									]
								}
							])
						}

						MessageBox.confirm('', {
							title: '市价模式',
							message: '下单成功，是否查看?',
							confirmButtonText: '查看',
							confirmButtonClass: 'red'
						}).then(action => {
							this.$store.commit('setToOrder', true) //chart 会watch 这个值，如果变为true就会跳转
							this.$store.commit('setOrderType', '1') //order 取这个值，显示持仓或挂单
						})
					} else {
                        if (res.msg === '下单失败,失败原因:余额不足' && params.payType === 1) {
                            MessageBox.confirm(' ', {
                                title: '市价模式',
                                message: '实盘账户余额不足，请立即充值',
                                confirmButtonText: '去充值',
                                confirmButtonClass: 'red'
                            }).then(action => {
                                if (action === 'confirm') {
                                    this.getTopupAuth()
                                }
                            })
                        } else {
						    MessageBox('挂单模式', res.msg)
                        }
                    }
                    Indicator.close()
                    this.orderKey = true
				})
				.catch((err) => {
                    console.log('err-->' ,err)
                    this.orderKey = true
                    Indicator.close()
					MessageBox('市价模式', err.msg)
				})
		},
		initBaseCart() {
			this.curAssetsIdx = 1
			this.jiao = false
			this.rate = 1
			this.curHand = 0
			this.curStopWinBeat = 0
			this.orderKey = true
        },
        getTopupAuth() {
            if (Object.keys(this.topupAuth).length === 0) {
                this.$router.push({
                    path: "/login",
                });
            } else if (this.topupAuth.identify === 1 && !this.topupAuth.cardState) {
                MessageBox.confirm("", {
                    title: "充值",
                    message: "为了您的资金安全，请前去绑卡",
                    confirmButtonText: "去绑定",
                    confirmButtonClass: "red"
                }).then(() => {
                    this.$router.push({
                        path: "/account/bindbank",
                    });
                });
            } else {
                window.location.href = "./account/paySelect.html";
            }
        }
	},
	watch: {
		getBasePeiZi(newer, old) {
			//初始化
			this.initBaseCart()
			//设置默认止盈为数组第1个
			this.curStopWinBeat = newer.assets[this.curAssetsIdx].stopWinBeat[1]
			//初始化手数为最小手数
			this.curHand = +newer.assets[0].handsMultiple[0]
		}
	},
	filters: {
		formatPoint(price, point) {
			if (price && point) {
				return price.toFixed(point)
			} else {
				return price
			}
		}
	}
}
</script>
<style scoped lang='scss'>
strong {
	width: rem(80px);
	text-align: left;
	font-size: rem(13px);
	white-space: nowrap;
	line-height: rem(28px);
}

.box {
	color: #666;
	min-width: rem(30px);
	padding-left: rem(5px);
	padding-right: rem(5px);
	width: auto;
	box-sizing: border-box;
	border-radius: rem(2px);
	border: 1px solid #aaaaaa;
}

.fix {
	min-width: rem(50px);
}

.arrow-box {
	border: 1px solid #aaaaaa;
	border-radius: rem(2px);
	width: rem(28px);
	line-height: rem(28px);
	height: rem(28px);
	box-sizing: border-box;
	color: #707284;
}

.line {
	border-bottom: 1px solid #f2f2f2;
}

.cube,
span,
input,
strong {
	height: rem(28px);
	line-height: rem(28px);
	margin-top: rem(5px);
	margin-bottom: rem(5px);
}

.cube {
	width: rem(30px);
	border: 1px solid #aaa;
	box-sizing: border-box;
	border-radius: rem(2px);
}

input {
	width: rem(80px);
	border: 0 none;
	outline: 0 none;
	text-align: center;
	background-color: transparent;
	color: #2e2d2d;
}

.buy-button {
	display: flex;
	width: 100%;
}

.buy-button p {
	color: #fff;
	flex: 1;
}

.buy-button img {
	vertical-align: rem(-5px);
}

.active {
	color: #fff;
	background-color: #ef9d2e;
	border-color: #ef9d2e;
}

.flex {
	display: flex;
}

.flex1 {
	flex: 1;
}

.fee strong {
	font-size: rem(13px);
	white-space: nowrap;
	margin-top: 0;
	margin-bottom: 0;
}

.fee span {
	font-size: rem(13px);
	margin-top: 0;
	margin-bottom: 0;
}
input {
	font-size: rem(13px);
}
</style>